/**
 * 
 */
/// <reference path="query.js">
// ========================================================================
function initAjax() {// 初始化ajax
	var xmlhttp;
	if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp = new XMLHttpRequest();
	} else {// code for IE6, IE5
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	return xmlhttp;
}
// 销毁对象
function divDestory() {
	var d = document.getElementById("infos");
	if (document.getElementById("page")) {
		var pa = document.getElementById("page");
		pa.parentNode.removeChild(pa);
	}
	if (d.getElementsByClassName("bookList")[0]) {
		var b = d.getElementsByClassName("bookList")[0];
		b.parentNode.removeChild(b);
	}
	if (d.getElementsByClassName("userList")[0]) {
		var u = d.getElementsByClassName("userList")[0];
		u.parentNode.removeChild(u);
	}
	if (d.getElementsByClassName("orderList")[0]) {
		var b = d.getElementsByClassName("orderList")[0];
		b.parentNode.removeChild(b);
	}
}
// =============================图书管理==================================================
var searchName, searchType, page, pageCount, sort, sortType, pageNum = 1, pageType;
function searchBook() {
	searchName = "";
	searchType = "id";
	pageCount = 10;
	getBookPageNum();
	page = 1;
	sort = "desc";
	sortType = "id";
	pageType = "book";
	getBooks();
}
// 获取图书页数
function getBookPageNum() {
	var xmlhttp = initAjax();
	var url = "../Admin_BookService?type=bookCount";
	var data={searchName:searchName,searchType:searchType,pageCount:pageCount};
	xmlhttp.open("post", url, true);
	xmlhttp.setRequestHeader("Content-Type",
			"application/x-www-form-urlencoded");
	xmlhttp.onreadystatechange = function() {
		// Ajax引擎状态为成功
		if (xmlhttp.readyState == 4) {
			// HTTP协议状态为成功
			if (xmlhttp.status == 200) {
				var data = eval(xmlhttp.responseText);
				pageNum = data[0].pageNum;
			}
		}
	};
	xmlhttp.send("data="+JSON.stringify(data));
}
// 获取图书列表
function getBooks() {
	var xmlhttp = initAjax();
	var url = "../Admin_BookService?type=search";
	var data={
			searchName:searchName,
			searchType:searchType,
			page:page,
			pageCount:pageCount,
			sort:sort,
			sortType:sortType};
	xmlhttp.open("post", url, true);
	xmlhttp.setRequestHeader("Content-Type",
			"application/x-www-form-urlencoded");
	xmlhttp.onreadystatechange = function() {
		// Ajax引擎状态为成功
		if (xmlhttp.readyState == 4) {
			// HTTP协议状态为成功
			if (xmlhttp.status == 200) {
				divDestory();
				var data = eval(xmlhttp.responseText);
				var div = document.getElementById("infos");
				var bookList = document.createElement("div");
				bookList.setAttribute("class", "bookList");
				div.appendChild(bookList);
				var deal_ul = document.createElement("div");
				deal_ul.setAttribute("class", "deal_ul");
				bookList.appendChild(deal_ul);
				a = document.createElement("a");
				a.setAttribute("href", "javascript:void(0)");
				a.setAttribute("onclick", "addBookPage()");
				a.innerHTML = "添加图书";
				deal_ul.appendChild(a);
				var table = document.createElement("table");
				bookList.appendChild(table);
				for (var i = -1; i < data.length; i++) {
					var tr = document.createElement("tr");
					table.appendChild(tr);
					var array;
					if (i == -1) {
						tr.setAttribute("class", "tr_title");
						array = new Array("书名", "作者", "出版社", "类型", "单价", "时间",
								"操作");
					} else {
						tr.setAttribute("class", "tr_info");
						array = new Array(data[i].title, data[i].author,
								data[i].publish.name, data[i].category.name,
								data[i].unprice, data[i].publishDate,
								data[i].id);
					}
					for (var j = 0; j < array.length; j++) {
						var th = document.createElement("th");
						th.innerHTML = array[j];
						th.setAttribute("class", "th_" + j);
						tr.appendChild(th);
						if (i != -1 && j == array.length - 1) {
							th.innerHTML = "";
							array = new Array("修改", "删除", "updateBookPage("
									+ array[j] + ")", "deleteBook(" + array[j]
									+ ")");
							for (var k = 0; k < (array.length / 2); k++) {
								var a = document.createElement("a");
								a.setAttribute("href", "javascript:void(0)");
								a.setAttribute("onclick", array[k + 2]);
								a.innerHTML = array[k];
								th.appendChild(a);
							}
						}
					}
				}
				var pageDiv = document.createElement("div");
				pageDiv.setAttribute("id", "page");
				div.appendChild(pageDiv);
				setPage(pageDiv, pageNum, page);
			}
		}
	};
	xmlhttp.send("data="+JSON.stringify(data));
}
function addBookPage() {
	var xmlhttp = initAjax();
	var url = "../Admin_BookService?type=bookInfo";
	var data = "data=0";
	xmlhttp.open("post", url, true);
	xmlhttp.setRequestHeader("Content-Type",
			"application/x-www-form-urlencoded");
	xmlhttp.onreadystatechange = function() {
		// Ajax引擎状态为成功
		if (xmlhttp.readyState == 4) {
			// HTTP协议状态为成功
			if (xmlhttp.status == 200) {
				var data = eval(xmlhttp.responseText);
				var category = document.getElementById("categoty");
				var publish = document.getElementById("publish");
				category.options.length = 0;
				publish.options.length = 0;
				for (var i = 0; i < data[0].length; i++) {
					category.options.add(new Option(data[0][i].name,
							data[0][i].id));
				}
				for (var i = 0; i < data[1].length; i++) {
					publish.options.add(new Option(data[1][i].name,
							data[1][i].id));
				}
				document.getElementById("bookPic").setAttribute("src", "");
				document.getElementById("bookTitle").value = "";
				document.getElementById("bookAuthor").value = "";
				document.getElementById("bookUnprice").value = "";
				document.getElementById("bookISBN").value = "";
				document.getElementById("bookDate").value = "";
				document.getElementById("bookWord").value = "";
				document.getElementById("bookC").value = "";
				document.getElementById("contentC").value = "";
				document.getElementById("authorC").value = "";
				document.getElementById("bookToc").value = "";
				document.getElementById("bookComit").setAttribute("onclick",
						"comitBook(0,'add')");

				document.getElementById("light").style.display = "block";
				document.getElementById('fade').style.display = "block";
			}
		}
	};
	xmlhttp.send(data);
}
// 修改图书页面
function updateBookPage(id) {
	var xmlhttp = initAjax();
	var url = "../Admin_BookService?type=bookInfo";
	var data = "data=" + id;
	xmlhttp.open("post", url, true);
	xmlhttp.setRequestHeader("Content-Type",
			"application/x-www-form-urlencoded");
	xmlhttp.onreadystatechange = function() {
		// Ajax引擎状态为成功
		if (xmlhttp.readyState == 4) {
			// HTTP协议状态为成功
			if (xmlhttp.status == 200) {
				var data = eval(xmlhttp.responseText);
				var category = document.getElementById("categoty");
				var publish = document.getElementById("publish");
				category.options.length = 0;
				publish.options.length = 0;
				for (var i = 0; i < data[0].length; i++) {
					category.options.add(new Option(data[0][i].name,
							data[0][i].id));
				}
				for (var i = 0; i < data[1].length; i++) {
					publish.options.add(new Option(data[1][i].name,
							data[1][i].id));
				}
				document.getElementById("bookPic").setAttribute("src",
						"../style/img/book_logo/" + data[2].picPath)
				document.getElementById("bookTitle").value = data[2].title;
				document.getElementById("bookAuthor").value = data[2].author;
				document.getElementById("bookUnprice").value = data[2].unprice;
				document.getElementById("categoty").value = data[2].category.id;
				document.getElementById("publish").value = data[2].publish.id;
				document.getElementById("bookISBN").value = data[2].ISBN;
				document.getElementById("bookDate").value = data[2].publishDate;
				document.getElementById("bookWord").value = data[2].worldsCount;
				document.getElementById("bookC").value = data[2].editorComment.replace(/<br\s*\/?>/g, "\n");
				document.getElementById("contentC").value = data[2].contentDescription.replace(/<br\s*\/?>/g, "\n");
				document.getElementById("authorC").value = data[2].authorDescription.replace(/<br\s*\/?>/g, "\n"); 
				document.getElementById("bookToc").value = data[2].toc.replace(/<br\s*\/?>/g, "\n"); 
				document.getElementById("bookComit").setAttribute("onclick",
						"comitBook(" + id + ",'update')");

				document.getElementById("light").style.display = "block";
				document.getElementById('fade').style.display = "block";
			}
		}
	};
	xmlhttp.send(data);
}
// 更新图书信息提交
function comitBook(id, active) {
	var xmlhttp = initAjax();
	var url;
	if (active == "update") {
		url = "../Admin_BookService?type=update";
	} else if (active == "add") {
		id = 0;
		url = "../Admin_BookService?type=add";
	}
	var img = document.getElementById("bookPic").src;
	img = img.substring(img.lastIndexOf("/") + 1);
	var data={
			id:id,
			picPath:img,
			title:document.getElementById("bookTitle").value,
			author:document.getElementById("bookAuthor").value,
			unprice:document.getElementById("bookUnprice").value,
			category:{id:document.getElementById("categoty").value,name:""},
			publish:{id:document.getElementById("publish").value,name:""},
			ISBN:document.getElementById("bookISBN").value,
			publishDate:document.getElementById("bookDate").value,
			worldsCount:document.getElementById("bookWord").value,
			editorComment:document.getElementById("bookC").value.split("\n").join("<br/>"),
			contentDescription:document.getElementById("contentC").value.split("\n").join("<br/>"),
			authorDescription:document.getElementById("authorC").value.split("\n").join("<br/>"),
			toc:document.getElementById("bookToc").value.split("\n").join("<br/>")
	};
	xmlhttp.open("post", url, true);
	xmlhttp.setRequestHeader("Content-Type",
			"application/x-www-form-urlencoded");
	xmlhttp.onreadystatechange = function() {
		// Ajax引擎状态为成功
		if (xmlhttp.readyState == 4) {
			// HTTP协议状态为成功
			if (xmlhttp.status == 200) {
				var data = eval(xmlhttp.responseText);
				if (data[0].update == "success") {
					alert("提交成功");
					document.getElementById("light").style.display = "none";
					document.getElementById("fade").style.display = "none";
					getBooks();
				} else {
					alert("提交失败");
				}
			}
		}
	};
	xmlhttp.send("data="+JSON.stringify(data));
}
// 删除图书
function deleteBook(id) {
	var xmlhttp = initAjax();
	var url = "../Admin_BookService?type=delete";
	var data = "data=" + id;
	xmlhttp.open("post", url, true);
	xmlhttp.setRequestHeader("Content-Type",
			"application/x-www-form-urlencoded");
	xmlhttp.onreadystatechange = function() {
		// Ajax引擎状态为成功
		if (xmlhttp.readyState == 4) {
			// HTTP协议状态为成功
			if (xmlhttp.status == 200) {
				var data = eval(xmlhttp.responseText);
				if (data[0].deleteBook == "success") {
					alert("删除成功");
					getBookPageNum();
					getBooks();
				} else {
					alert("删除失败");
				}
			}
		}
	};
	xmlhttp.send(data);
}
// ==================================用户管理====================================================
function getUserInfoPage() {
	pageCount = 20;
	page = 1;
	getUserPageNum();
	pageType = "user";
	getUsers();
}
// 获取用户页数
function getUserPageNum() {
	var xmlhttp = initAjax();
	var url = "../Admin_UserServlet?type=userCount";
	var data = "data=" + pageCount;
	xmlhttp.open("post", url, true);
	xmlhttp.setRequestHeader("Content-Type",
			"application/x-www-form-urlencoded");
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4) {
			if (xmlhttp.status == 200) {
				var data = eval(xmlhttp.responseText);
				pageNum = data[0].userPageNum;
			}
		}
	};
	xmlhttp.send(data);
}
// 刷新用户界面
function getUsers() {
	var xmlhttp = initAjax();
	var url = "../Admin_UserServlet?type=userInfo";
	var data={
			page:page,
			pageCount:pageCount
	};
	xmlhttp.open("post", url, true);
	xmlhttp.setRequestHeader("Content-Type",
			"application/x-www-form-urlencoded");
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4) {
			if (xmlhttp.status == 200) {
				divDestory();
				var data = eval(xmlhttp.responseText);
				var div = document.getElementById("infos");
				var userList = document.createElement("div");
				userList.setAttribute("class", "userList");
				div.appendChild(userList);
				var array = new Array("账户", "姓名", "地址", "电话", "邮箱", "角色",
						"账户状态", "操作");
				var table = document.createElement("table");
				table.setAttribute("id", "userTable");
				userList.appendChild(table);
				for (var i = -1; i < data[2].length; i++) {
					var tr = document.createElement("tr");
					tr.setAttribute("class", "tr_" + i);
					table.appendChild(tr);
					if (i == -1) {
						for (var j = 0; j < array.length; j++) {
							var th = document.createElement("th");
							th.innerHTML = array[j];
							tr.appendChild(th);
						}
					} else {
						array = new Array(data[2][i].userId,
								data[2][i].userName, data[2][i].address,
								data[2][i].userPhone, data[2][i].userEmail,
								data[2][i].userRoleId, data[2][i].userStateId);
						for (var j = 0; j < array.length; j++) {
							var th = document.createElement("th");
							tr.appendChild(th);
							if (j < array.length - 2) {
								th.innerHTML = array[j];
							} else {
								var select = document.createElement("select");
								select.setAttribute("class", "select");
								th.appendChild(select);
								for (var k = 0; k < data[j - 5].length; k++) {
									select.options.add(new Option(
											data[j - 5][k].name,
											data[j - 5][k].id));
								}
								select.value = array[j];
							}
						}
						array = new Array("修改", "删除", "updateUser("
								+ data[2][i].id + "," + i + ")", "deleteUser("
								+ data[2][i].id + ")");
						var th = document.createElement("th");
						tr.appendChild(th);
						for (var j = 0; j < (array.length / 2); j++) {
							var a = document.createElement("a");
							a.setAttribute("href", "javascript:void(0)");
							a.setAttribute("onclick", array[j + 2]);
							a.innerHTML = array[j];
							th.appendChild(a);
						}
					}
				}
				var pageDiv = document.createElement("div");
				pageDiv.setAttribute("id", "page");
				div.appendChild(pageDiv);
				setPage(pageDiv, pageNum, page);
			}
		}
	};
	xmlhttp.send("data="+JSON.stringify(data));
}
// 修改用户
function updateUser(id, rows) {
	var xmlhttp = initAjax();
	var url = "../Admin_UserServlet?type=updateUser";
	var tr = document.getElementById("userTable").getElementsByClassName(
			"tr_" + rows)[0];
	var data={
			id:id,
			userRoleId:tr.getElementsByClassName("select")[0].value,
			userStateId:tr.getElementsByClassName("select")[1].value
	};
	xmlhttp.open("post", url, true);
	xmlhttp.setRequestHeader("Content-Type",
			"application/x-www-form-urlencoded");
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4) {
			if (xmlhttp.status == 200) {
				var data = eval(xmlhttp.responseText);
				if (data[0].updateUser == "success") {
					alert("修改成功");
					getUsers();
				} else {
					alert("修改失败");
				}
			}
		}
	};
	xmlhttp.send("data="+JSON.stringify(data));
}
// 删除用户
function deleteUser(id) {
	var xmlhttp = initAjax();
	var url = "../Admin_UserServlet?type=deleteUser";
	var data = "data=" + id;
	xmlhttp.open("post", url, true);
	xmlhttp.setRequestHeader("Content-Type",
			"application/x-www-form-urlencoded");
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4) {
			if (xmlhttp.status == 200) {
				var data = eval(xmlhttp.responseText);
				if (data[0].deleteUser == "success") {
					alert("删除成功");
					getUserPageNum();
					getUsers();
				} else {
					alert("删除失败");
				}
			}
		}
	};
	xmlhttp.send(data);
}
// =================================订单==================================================
function getOrderPage() {
	pageType = "order";
	pageCount = 5;
	page = 1;
	getOrderCount();
	getOrders();
}
// 获取订单页数
function getOrderCount() {
	var xmlhttp = initAjax();
	var url = "../Admin_OrderService?type=orderCount";
	var data = "data=" + pageCount;
	xmlhttp.open("post", url, true);
	xmlhttp.setRequestHeader("Content-Type",
			"application/x-www-form-urlencoded");
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4) {
			if (xmlhttp.status == 200) {
				var data = eval(xmlhttp.responseText);
				pageNum = data[0].userPageNum;
			}
		}
	};
	xmlhttp.send(data);
}
// 查询用户订单
function getOrders() {
	var xmlhttp = initAjax();
	var url = "../Admin_OrderService?type=orderInfo";
	var data={
			page:page,
			pageCount:pageCount
	};
	xmlhttp.open("post", url, true);
	xmlhttp.setRequestHeader("Content-Type",
			"application/x-www-form-urlencoded");
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4) {
			if (xmlhttp.status == 200) {
				divDestory();
				var data = eval(xmlhttp.responseText);
				var div = document.getElementById("infos");
				var orderList = document.createElement("div");
				orderList.setAttribute("class", "orderList");
				div.appendChild(orderList);

				var array = new Array("订单信息", "收货人", "订单金额", "订单时间", "当前状态",
						"操作");
				var ul_t = document.createElement("ul");
				ul_t.setAttribute("class", "order_title");
				orderList.appendChild(ul_t);
				for (var k = 0; k < array.length; k++) {
					var li = document.createElement("li");
					li.setAttribute("class", "li_" + k);
					li.innerHTML = array[k];
					ul_t.appendChild(li);
				}

				for (var i = 0; i < data.length; i++) {
					var ul = document.createElement("ul");
					orderList.appendChild(ul);
					ul.setAttribute("class", "order_name");
					array = new Array("订单号:" + data[i].id,
							data[i].user.userName, data[i].totalPrice,
							(data[i].orderDate).replace(".0", ""), "订单完成",
							"删除", data[i].id);
					for (var k = 0; k < array.length - 1; k++) {
						var li = document.createElement("li");
						li.setAttribute("class", "li_" + k);
						if (k == array.length - 2) {
							var a = document.createElement("a");
							a.setAttribute("href", "javascript:void(0)");
							a.setAttribute("onclick", "deleteOrder("
									+ array[k + 1] + ")");
							li.appendChild(a);
							a.innerHTML = array[k];
						} else {
							li.innerHTML = array[k];
						}
						ul.appendChild(li);
					}

					for (var j = 0; j < data[i].orderBooks.length; j++) {
						array = new Array(data[i].orderBooks[j].book.title,
								data[i].orderBooks[j].book.unprice + "x"
										+ data[i].orderBooks[j].quantity, "",
								"","查看商品",data[i].orderBooks[j].book.id);
						var ul_info = document.createElement("ul");
						ul_info.setAttribute("class", "order_info");
						orderList.appendChild(ul_info);
						for (var k = 0; k < array.length-1; k++) {
							var li = document.createElement("li");
							li.setAttribute("class","info_"+k);
							if(k==array.length-2){
								var a = document.createElement("a");
								a.setAttribute("target","view_frame");
								a.setAttribute("href","../pages/bookInfo.jsp?book="+array[k+1]);
								a.innerHTML =array[k];
								li.appendChild(a);
							}else{
								li.innerHTML = array[k];
							}
							ul_info.appendChild(li);
						}
					}
				}
				var pageDiv = document.createElement("div");
				pageDiv.setAttribute("id", "page");
				div.appendChild(pageDiv);
				setPage(pageDiv, pageNum, page);
			}
		}
	};
	xmlhttp.send("data="+JSON.stringify(data));
}
function deleteOrder(id) {
	var xmlhttp = initAjax();
	var url = "../Admin_OrderService?type=orderDelete";
	var data = "data=" + id;
	xmlhttp.open("post", url, true);
	xmlhttp.setRequestHeader("Content-Type",
			"application/x-www-form-urlencoded");
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4) {
			if (xmlhttp.status == 200) {
				var data = eval(xmlhttp.responseText);
				if(data[0].deleteOrder=="success"){
					alert("删除成功");
					getOrderCount();
					getOrders();
				}else{
					alert("删除失败");
				}
			}
		}
	};
	xmlhttp.send(data);
}
// ===============================分页==============================================
function setPage(container, count, pageindex) {
	var container = container;
	var count = count;
	var pageindex = pageindex;
	var a = [];
	// 总页数少于10 全部显示,大于10 显示前3 后3 中间3 其余....
	if (pageindex == 1) {
		a[a.length] = "<a href=\"#\" class=\"prev unclick\">上一页</a>";
	} else {
		a[a.length] = "<a href=\"#\" class=\"prev\">上一页</a>";
	}
	function setPageList() {
		if (pageindex == i) {
			a[a.length] = "<a href=\"#\" class=\"on\">" + i + "</a>";
		} else {
			a[a.length] = "<a href=\"#\">" + i + "</a>";
		}
	}
	// 总页数小于10
	if (count <= 10) {
		for (var i = 1; i <= count; i++) {
			setPageList();
		}
	}
	// 总页数大于10页
	else {
		if (pageindex <= 4) {
			for (var i = 1; i <= 5; i++) {
				setPageList();
			}
			a[a.length] = "...<a href=\"#\">" + count + "</a>";
		} else if (pageindex >= count - 3) {
			a[a.length] = "<a href=\"#\">1</a>...";
			for (var i = count - 4; i <= count; i++) {
				setPageList();
			}
		} else { // 当前页在中间部分
			a[a.length] = "<a href=\"#\">1</a>...";
			for (var i = pageindex - 2; i <= pageindex + 2; i++) {
				setPageList();
			}
			a[a.length] = "...<a href=\"#\">" + count + "</a>";
		}
	}
	if (pageindex == count) {
		a[a.length] = "<a href=\"#\" class=\"next unclick\">下一页</a>";
	} else {
		a[a.length] = "<a href=\"#\" class=\"next\">下一页</a>";
	}
	container.innerHTML = a.join("");
	// 事件点击
	var pageClick = function() {
		var oAlink = container.getElementsByTagName("a");
		var inx = pageindex; // 初始的页码
		oAlink[0].onclick = function() { // 点击上一页
			if (inx == 1) {
				return false;
			}
			inx--;
			getPage(inx);
			setPage(container, count, inx);
			return false;
		}
		for (var i = 1; i < oAlink.length - 1; i++) { // 点击页码
			oAlink[i].onclick = function() {
				inx = parseInt(this.innerHTML);
				getPage(inx);
				setPage(container, count, inx);
				return false;
			}
		}
		oAlink[oAlink.length - 1].onclick = function() { // 点击下一页
			if (inx == count) {
				return false;
			}
			inx++;
			getPage(inx);
			setPage(container, count, inx);
			return false;
		}
	}()
}
function getPage(p) {
	page = p;
	switch (pageType) {
	case "book":
		getBooks();
		break;
	case "user":
		getUsers();
		break;
	case "order":
		getOrders();
		break;
	default:
		break;
	}
}